package com.Akronmcp.hopMessage;

import java.util.Calendar;
import java.util.Date;

import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

/**时间监听器类,用来控制定时公告线程的开关,并由此来开启全部公告线程*/
public class HmTimer {

	
	static int interval = 20;
	
	
	static BukkitTask thread;
	
	public static void setInterval(int interval)
	{//监听时间的间隔
		HmTimer.interval = interval;
	}
	
	public static void setOff()
	{
		if(thread!=null)
	    thread.cancel();
	}

	/**开启时间监听器*/
	public static void goStart()
	{
		
	  if(thread!=null)
	  thread.cancel();
		  
	  thread = new BukkitRunnable() {
			
			@Override
			public void run() 
			{
			  
			  
			  Date now = new Date();
			  
			  for(HopMess hm:HopMess.hmMap.values())
			  {//遍历公告线程组
				  
				  Date d1 = hm.getBeginDate();
				  Date d2 = hm.getEndDate();
				  
				  boolean t1 = false;
				  //条件1,符合在日期区间内
				  
				  if(d1==null&&d2==null)
				  {
					  t1 = true;
					  
				  }else if(d1==null&&d2!=null&&d2.after(now))
				  {
					  t1 = true;
				  }else if(d1!=null&&d1.before(now)&&d2==null)
				  {
					  t1 = true;
				  }else if(d1!=null&&d1.before(now)&&d2!=null&&d2.after(now))
				  {
					  t1 = true;
				  }else
				  {
					  hm.goOn(false);
					  continue;
				  }
				  
				  
				  boolean t2 = false;
				  //条件2,符合在每日时间区间内
				  
				  Calendar fc1 = hm.getDayBeginDate();
				  Calendar fc2 = hm.getDayEndDate();
				  //每日时间区间
				  
				  Date c1 = null;
				  Date c2 = null;
	  
				  
				  if(fc1!=null)
				  {//同化日期,进行比对
					 Calendar nowc=Calendar.getInstance();
					 nowc.set(Calendar.HOUR_OF_DAY,fc1.get(Calendar.HOUR_OF_DAY));
					 nowc.set(Calendar.MINUTE,fc1.get(Calendar.MINUTE)-1);
					 
					c1= nowc.getTime();
		
				  }
				  
				  if(fc2!=null)
				  {
					 Calendar nowc=Calendar.getInstance();
					 nowc.set(Calendar.HOUR_OF_DAY,fc2.get(Calendar.HOUR_OF_DAY));
					 nowc.set(Calendar.MINUTE,fc2.get(Calendar.MINUTE));
					 
					 c2= nowc.getTime();

				  }
				  
				  
				  
				  if(c1==null&&c2==null)
				  {//筛选条件,且允许只存在一端
					  t2 = true;
					  
				  }else if(c1==null&&c2!=null&&c2.after(now))
				  {
					  t2 = true;
				  }else if(c1!=null&&c1.before(now)&&fc2==null)
				  {
					  t2 = true;
				  }else if(c1!=null&&c1.before(now)&&c2!=null&&c2.after(now))
				  {
					  t2 = true;
				  }else
				  {//不符则关闭
					  hm.goOn(false);
					  continue;
				  }
				  
				  if(t1&&t2)
				  hm.goOn(true);
			
					  
				  
			  }
				
			  
			  
			}
		}.runTaskTimerAsynchronously(HmM.getPlugin(HmM.class), 5L, interval);
		
	}
	
}
